<?php

namespace app\madmin\service;

use app\madmin\model\CollageItem;
use app\madmin\model\Order;
use app\madmin\model\OrderCommodity;
use app\utils\TrimData;
use think\db\Query;
use think\Validate;
use think\model\Relation;
use think\Exception;
use think\facade\Db;
use app\madmin\model\Collage;
use app\madmin\model\GroupCommodity;
use app\madmin\model\GroupCommoditySku;

class CollageService
{

    private function buildWhere(array $data)
    {
        $where = [];
        !empty($data['status']) && $where[] = ['status' , '=', $data['status']];
        return $where;
    }

    /**
     * 查询列表
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function index($page = 1, $size = 10, $search = [])
    {
        $list = Collage::where($this->buildWhere($search))->with(['commodity', 'groupCommodity'])->order('id DESC')->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }

    public function read($id)
    {
        $collage = Collage::with(['collageItem' => function ($sql) {
            $sql->with(['user']);
        }, 'groupCommodity', 'orderCommodity', 'user'])->find($id);
        $collage['order'] = Db::name('order')->alias('a')
            ->join('order_commodity b', 'a.id = b.order_id', 'right')
            ->join('commodity c', 'b.commodity_id = c.id', 'left')
            ->join('sku d', 'b.sku_id = d.id', 'left')
            ->where('b.collage_id', $id)
            ->select();
        return [HTTP_SUCCESS, $collage];
    }

    /**
     * @param $id
     * @return array
     * @throws
     */
    public function update($id)
    {
        $collage = Collage::find($id);
        if ($collage['status'] != 1) {
            throw new Exception('团状态不对！', HTTP_INVALID);
        }
        $this->checkStock($collage);
        $robot = $collage['success_num'] - $collage['num'];
        while ($robot > 0) {
            
            $user = [1, '/people/'.rand(1, 200).".jpg"];

            CollageItem::create([
                'gc_id' => $collage['gc_id'],
                'collage_id' => $id,
                'user_id' => json_encode($user),
                'commodity_id' => $collage['commodity_id'],
                'sku_id' => $collage['sku_id'],
                'create_time' => date("Y-m-d H:i:s", time()),
                'is_robot' => 1
            ]);
            $robot --;
        }
        Collage::where('id', $id)->update(['status' => 2]);
        $this->decStock($collage);
        return [HTTP_SUCCESS, 1];
    }


    public function checkStock($value)
    {
        if (is_null($value['sku_id'])) {
            $commodity = Db::name('group_commodity')
                ->field("activity_stock")
                ->where('id', $value['gc_id'])
                ->find();
        } else {
            $commodity = Db::name('group_commodity_sku')
                ->field("activity_stock")
                ->where('gc_id', $value['gc_id'])
                ->where('sku_id', $value['sku_id'])
                ->find();
        }
        $group_stock = $commodity['activity_stock'];
        $count = OrderCommodity::find($value['oc_id'])['count'];
        $items_count = Db::name('collage_item')->alias('a')->join('order_commodity b', 'a.oc_id = b.id' )->where('a.collage_id', $value['id'])->count('b.count');

        if ($group_stock < ($count + $items_count)) {
            throw new Exception('库存不足！', HTTP_INVALID);
        }
    }


    public function decStock($value)
    {
        $num = Db::name('order_commodity')->find($value['oc_id'])['count'];
        // 减拼团库存
        if (is_null($value['sku_id'])) {
            Db::name('group_commodity')
                ->where('id', $value['gc_id'])
                ->dec("activity_stock", $num)->update();
        } else {
            Db::name('group_commodity_sku')
                ->where('gc_id', $value['gc_id'])
                ->where('sku_id', $value['sku_id'])
                ->dec("activity_stock", $num)->update();
        }
    }

}
